package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.context.SessionConstants;
import cn.livingCloud.dto.CaseReportFormDto;
import cn.livingCloud.dto.JsonDto;
import cn.livingCloud.entity.core.CaseRecord;
import cn.livingCloud.entity.core.CaseRecordType;
import cn.livingCloud.entity.core.CaseStatus;
import cn.livingCloud.entity.core.Employee;
import cn.livingCloud.repository.CaseRecordMapper;
import cn.livingCloud.repository.EmployeeMapper;
import cn.livingCloud.utils.SessionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 上报案件
 * Created by 唐旭 on 2016/6/6.
 */
public class CaseReporter extends CaseOperator {
    protected transient EmployeeMapper employeeMapper = BeanProvider.getBean(EmployeeMapper.class);
    protected transient CaseRecordMapper recordMapper = BeanProvider.getBean(CaseRecordMapper.class);

    private CaseReportFormDto formDto;
    private Employee employee;
    private List<Employee> leaders;

    public CaseReporter(CaseReportFormDto formDto) {
        super(formDto);
        this.formDto = formDto;
        employee = SessionUtils.getAttribute(Employee.class, SessionConstants.EMPLOYEE_KEY);
    }

    @Override
    protected JsonDto operation() {
        super.aCase.setStatus(CaseStatus.REPORT);
        if (employee != null && employee.isInspector() && !formDto.isReportPlatform()) {
            super.aCase.setOwnerId(buildEmployeeUuidArray(leaders).toString());
        } else {
            super.aCase.setOwnerId(null);
        }
        //查询当前处理人是否有三次上报
        List<CaseRecord> caseRecord = recordMapper.findDistinctCaseRecordReport(aCase.getUuid(), CaseRecordType.REPORT, 3);
        if (caseRecord.size() > 0) {
            super.aCase.setDisableStatus(CaseStatus.REPORT);
        }
        //发送模板消息
        msgService.sendReportMsg(aCase, formDto.getContent());
        JsonDto jsonDto = new JsonDto();
        jsonDto.setState(true);
        return jsonDto;
    }

    @Override
    protected List<Employee> getNewOwners() {
        if (employee != null && employee.isInspector() && !formDto.isReportPlatform()) {
            leaders = employeeMapper.findCurrentDeptLeader(employee.getDeptUuid());
            return leaders;
        }
        return new ArrayList<>();
    }
}
